/*
 * @Author: rxn 1003312535@qq.com
 * @Date: 2024-02-29 16:33:16
 * @LastEditors: rxn 1003312535@qq.com
 * @LastEditTime: 2024-12-24 19:48:01
 * @FilePath: \vue3-progect\src\store\modules\user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from "pinia";
import { router } from "@/router/setupRouter.js";

//- Store
import { useMenuStore } from "@/store/modules/menu";
//- 枚举
import { PageEnum } from "@/enums/pageEnum";
import { APP_USER_INFO } from "@/enums/cacheEnum";
//- 缓存
import { createLocalStorage } from "@/utils/cache";
let ls = createLocalStorage();
//- api
import { loginApi } from "@/api/login";

interface State {
	userInfo: Object | null;
	token: String | "";
	roleList: String[];
}

export const useUser = defineStore("user", {
	state: (): State => {
		return {
			userInfo: null,
			token: "",
			roleList: []
		};
	},
	getters: {
		getUserInfo(state): Object {
			return state.userInfo || ls.getItem("APP_USER_INFO") || {};
		},
		getToken(state): String {
			return state.token || ls.getItem("APP_USER_INFO") || {};
		}
	},
	actions: {
		//登录
		async login(params) {
			console.log(params, "params----params");
			try {
				// 调用登录接口
				let result = { userInfo: { userId: 1 } };
				this.setUserInfo(result);
				// // 调用登录接口
				// loginApi(params);
				// this.setUserInfo(params);
				//获取动态路由、设置
				const menuStore = useMenuStore();
				menuStore.getMenuList();
				let toPath = this.userInfo.homePath || PageEnum.BASE_HOME;
				menuStore.getAsideMenuList({ menuId: this.userInfo.defaultmenu || 1 });
				//跳转路由
				router.replace({ path: toPath });
			} catch (error) {
				console.log("@FilePath: /vue3-progect/src/store/user.js: ", error);
			}
		},
		//设置 用户信息
		setUserInfo(payload) {
			try {
				this.userInfo = payload.userInfo;
				ls.setItem(APP_USER_INFO, this.userInfo);
			} catch (error) {
				console.log("设置 用户信息：", error);
			}
		},
		//退出
		async quit() {
			// 调用退出接口
			try {
				//清除缓存
				ls.clear();
				//清 store
				this.resetState();
				//跳转路由
				router.replace({
					path: this.resetState.BASE_LOGIN || PageEnum.BASE_LOGIN
				});
			} catch (error) {
				console.log("@FilePath: /vue3-progect/src/store/user.js: ", error);
			}
		},
		//重置Store
		resetState() {
			this.userInfo = null;
			this.token = "";
			this.roleList = [];
		}
	}
});

// //订阅
// useUser.$subscribe((mutation, state) => {
//   console.log(mutation, state, "user订阅");
//   // ls.setItem('a',mutation)
// });
